//
//  UIViewController+KeyboardObserver.m
//  nav
//
//  Created by wjxfhxy on 15/8/11.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "UIViewController+KeyboardObserver.h"

typedef NS_ENUM (NSInteger,KeyboardResponseStatus)
{
    KeyBoardResponseStatusNone = 0,
    KeyBoardResponseStatusWillVisiable = 1,
    KeyBoardResponseStatusDidVisiable = 2,
    
    KeyboardResponseStatusIOS8ErrorStatus = 4
    
    /*
    //正确得键盘响应顺序是willChangeFrame -> show;willChangeFrame -> show;;;;;willChangeFrame -> hidden;
    //但有时会变成willChangeFrame ->willChangeFrame ->show－>show;willChangeFrame -> hidden;可能是ios7bug
    KeyBoardResponseStatusWillChangeFrame = 4
     */
};

@interface UIViewController (KeyboardObserverInternal)

@property(nonatomic,assign) KeyboardResponseStatus keyboardResponseStatus;

@end

@implementation UIViewController (KeyboardObserver)

- (void)setKeyboardResponseStatus:(KeyboardResponseStatus)keyboardResponseStatus
{
    [self setAssociatedRetainNonatomicValue:@(keyboardResponseStatus) withKey:"keyboardResponseStatus"];
}

- (KeyboardResponseStatus)keyboardResponseStatus
{
    return [[self associatedValueForKey:"keyboardResponseStatus"] integerValue];
}

- (void)setKeyboardOffSet:(CGFloat)keyboardOffSet
{
    [self setAssociatedRetainNonatomicValue:@(keyboardOffSet) withKey:"keyboardOffSet"];
}

- (CGFloat)keyboardOffSet
{
    return [[self associatedValueForKey:"keyboardOffSet"] floatValue];
}

- (void)observerKeyboardWillShow:(NSNotification *)noti
{
    NSArray *ar = [XUINavigationController navigationController].viewControllers;
    NSUInteger index = [ar indexOfObject:self];
    if([ar containsObject:self])
    {
        if(index != ar.count - 1)
            return;
    }
    
    [self keyboardWillShow:noti];
}

- (void)observerKeyboardDidShow:(NSNotification *)noti
{
    NSArray *ar = [XUINavigationController navigationController].viewControllers;
    NSUInteger index = [ar indexOfObject:self];
    if([ar containsObject:self])
    {
        if(index != ar.count - 1)
            return;
    }
    
    [self keyboardDidShow:noti];
}

- (void)observerKeyboardWillHide:(NSNotification *)noti
{
    NSArray *ar = [XUINavigationController navigationController].viewControllers;
    NSUInteger index = [ar indexOfObject:self];
    if([ar containsObject:self])
    {
        if(index != ar.count - 1)
            return;
    }
    
    [self keyboardWillHide:noti];
}

//- (void)observerkeyboardFrameWillChange:(NSNotification *)noti
//{
//    if(self.view.hidden == YES || self.view.userInteractionEnabled == NO|| self.view.left < 0  /*||[CViewBaseViewController getTopViewController] != self */)
//        return;
//    
//    [self keyboardFrameWillChange:noti];
//}

- (BOOL)keyboardWillShow:(NSNotification *)noti
{
    CGRect frame = [(NSValue *) [[noti userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat nKboffSet = 0;
    
    if(UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
    {
        nKboffSet = frame.size.height;
        
        if ((self.keyboardResponseStatus & KeyBoardResponseStatusWillVisiable)== KeyBoardResponseStatusWillVisiable)
        {
            
            if((self.keyboardResponseStatus & KeyboardResponseStatusIOS8ErrorStatus) == KeyboardResponseStatusIOS8ErrorStatus)
            {
                self.keyboardResponseStatus -= KeyBoardResponseStatusNone;
                [self keyboardDidShow:noti];
            }
            
            if(frame.size.height != self.keyboardOffSet && (self.keyboardResponseStatus & KeyBoardResponseStatusDidVisiable)== KeyBoardResponseStatusDidVisiable)
            {
                CGFloat changeSize = self.keyboardOffSet - frame.size.height;
                CGFloat duration = [[[noti userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
                UIViewAnimationCurve curve = [[[noti userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
                
                self.keyboardOffSet = frame.size.height;
                
                [self keyboardWillChangeSize:changeSize withAnimationDuration:duration curve:curve];
            }
            
            return NO;
        }
        
        
    }
    else
    {
        nKboffSet = frame.size.width;
        if ((self.keyboardResponseStatus & KeyBoardResponseStatusWillVisiable)== KeyBoardResponseStatusWillVisiable)
        {
            return NO;
        }
    }
    
    self.keyboardOffSet = nKboffSet;
    
    self.keyboardResponseStatus |= KeyBoardResponseStatusWillVisiable;
    
    return YES;
}

- (BOOL)keyboardDidShow:(NSNotification *)noti
{
//    self.keyboardResponseStatus ^= KeyBoardResponseStatusWillChangeFrame;
    
    if(self.keyboardResponseStatus == KeyBoardResponseStatusNone)
    {
        self.keyboardResponseStatus = KeyboardResponseStatusIOS8ErrorStatus;
        return NO;
    }
    
    if((self.keyboardResponseStatus & KeyBoardResponseStatusDidVisiable) != KeyBoardResponseStatusDidVisiable)
    {
        self.keyboardResponseStatus |= KeyBoardResponseStatusDidVisiable;
        
        return YES;
    }
    
    return NO;
}

- (BOOL)keyboardWillHide:(NSNotification *)noti
{
    if ((self.keyboardResponseStatus & KeyBoardResponseStatusDidVisiable) == KeyBoardResponseStatusDidVisiable)
    {
        self.keyboardResponseStatus = KeyBoardResponseStatusNone;
        return YES;
    }
    self.keyboardResponseStatus = KeyBoardResponseStatusNone;
    return NO;
}

- (void)keyboardWillChangeSize:(CGFloat)changeSize withAnimationDuration:(CGFloat)duration curve:(UIViewAnimationCurve)curve
{
    
}

/*
- (BOOL)keyboardFrameWillChange:(NSNotification *)noti
{
    if ((self.keyboardResponseStatus & KeyBoardResponseStatusWillChangeFrame) == KeyBoardResponseStatusWillChangeFrame)
    {
#ifdef DEBUG
        NSLog(@"error keyBoard response");
#endif
        [self keyboardDidShow:noti];
        
        //        return NO;
    }
    else
        self.keyboardResponseStatus |= KeyBoardResponseStatusWillChangeFrame;
    
    CGRect frame1 = [(NSValue *) [[noti userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect frame2 = [(NSValue *) [[noti userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    if(UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
    {
        if (frame1.size.height != frame2.size.height)
        {
            self.keyboardOffSet = frame1.size.height;
            return YES;
        }
    }
    else
    {
        if (frame1.size.width != frame2.size.width)
        {
            self.keyboardOffSet = frame1.size.width;
            return YES;
        }
    }
    return NO;
}
*/

- (void)addKeyboardObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observerKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observerKeyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observerKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observerkeyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)removeKeyboardObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

+ (void)closeKeyBoard
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

@end
